//
//  LSyueBanManageViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2019/7/25.
//  Copyright © 2019 wpkj. All rights reserved.
//

#import "LSYueBanMangeVC.h"
#import "JSONUtils.h"
#import "NiWenListCell.h"
#import "LSLiuChengTuVC.h"
#import "LSYueBanInfoVC.h"
#define SelectViewWidth (147/3*2)
#define SelectViewHeight (100)

#define headerSearchViewHeight 103
#define CountPerPage 10
@interface LSYueBanMangeVC () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, assign) BOOL nwglXialaImageViewIsShowing;
@property (nonatomic, strong) UIImageView *nwglXialaImageView;
@property (nonatomic, strong) UIView *backgroundAlphaView;
@property (nonatomic, strong) NSArray <NSDictionary *> *selectButtonsArray;

@property (nonatomic, strong) UITableView *yueBanTableView;
@property (nonatomic, strong) NSMutableArray *dataArrayM;

@property (nonatomic, strong) UITextField *yueBanName;

@property (nonatomic, strong) UITextField *yueBanNum;

@property (nonatomic, assign) NSInteger tablePage;

@property (nonatomic, strong) UIButton *chooseBtn;

@property (nonatomic, strong) NSDictionary *selectDict;

@end

static NSString *yueBanTableViewCellID = @"yueBanTableViewCellID";

@implementation LSYueBanMangeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"阅办管理";
    
    UIBarButtonItem *moreBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"more"] style:UIBarButtonItemStylePlain target:self action:@selector(moreBarButtonItemClick)];
    self.navigationItem.rightBarButtonItem = moreBarButtonItem;
    self.nwglXialaImageViewIsShowing = false;
    [self setUpHeaderSearchView];
    [self.view addSubview:self.yueBanTableView];
    WS
    self.yueBanTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.tablePage = 1;
        [weakSelf loadData];
    }];
    self.yueBanTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.tablePage++;
        [weakSelf loadData];
    }];
    [self.yueBanTableView.mj_header beginRefreshing];
}
- (void)setUpHeaderSearchView {
    UIView *headerSearchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, headerSearchViewHeight)];
    headerSearchView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:headerSearchView];
    UIView *headerViewBottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, headerSearchViewHeight-0.5, ScreenWidth, 0.5)];
    headerViewBottomLineView.backgroundColor = hexColor(CCCCCC);
    [headerSearchView addSubview:headerViewBottomLineView];
    
    // 拟文名
    UITextField *nameTF = [[UITextField alloc] initWithFrame:CGRectMake(15, 5+4, (ScreenWidth-30), 36)];
    self.yueBanName = nameTF;
    nameTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12];
    nameTF.layer.borderColor = hexColor(dbdbdb).CGColor;
    nameTF.layer.borderWidth = 1;
    nameTF.returnKeyType = UIReturnKeySearch;
    nameTF.placeholder = @"请输入文件标题";
    nameTF.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 1)];
    nameTF.leftViewMode = UITextFieldViewModeAlways;
    [headerSearchView addSubview:nameTF];
    
    
    UITextField *cardNumberTF = [[UITextField alloc] initWithFrame:CGRectMake(15, 54+4, ScreenWidth-30-55-15, 36)];
    self.yueBanNum = cardNumberTF;
    cardNumberTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12];
    cardNumberTF.layer.borderColor = hexColor(dbdbdb).CGColor;
    cardNumberTF.layer.borderWidth = 1;
    cardNumberTF.returnKeyType = UIReturnKeySearch;
    cardNumberTF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    cardNumberTF.placeholder = @"请输入原文编号";
    cardNumberTF.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 1)];
    cardNumberTF.leftViewMode = UITextFieldViewModeAlways;
    [headerSearchView addSubview:cardNumberTF];
    
    UIButton *searchButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-15-55, 54+4, 55, 36)];
    searchButton.layer.cornerRadius = 4;
    searchButton.layer.masksToBounds = true;
    searchButton.backgroundColor = NAV_COLOR;
    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    searchButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12];
    [searchButton addTarget:self action:@selector(loadData) forControlEvents:UIControlEventTouchUpInside];
    [headerSearchView addSubview:searchButton];
}
- (void)loadData {
    [self.view endEditing:YES];
    NSDictionary *param = @{@"fileTitle":[self.yueBanName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]],@"fileNum":[self.yueBanNum.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]],@"rows":[NSString stringWithFormat:@"%d",CountPerPage],@"page":[NSString stringWithFormat:@"%ld",(long)self.tablePage]};
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:[NSString stringWithFormat:@"%@&token=%@",YbManageList,[UserInfoModel sharedInstance].token] param:param completionHandler:^(id responseObject, NSError *connectionError) {
        NSLog(@"参数：%@",param);
        [hud hideAnimated:true];
        if (!connectionError) {
            NSNumber *status = [responseObject objectForKey:@"status"];
            if (self.tablePage == 1) {
                [self.yueBanTableView.mj_header endRefreshing];
                [self.dataArrayM removeAllObjects];
            }
            if (status.integerValue == 200) {
                NSArray *dataArray = [responseObject objectForKey:@"data"];
                [self.dataArrayM addObjectsFromArray:dataArray];
                if (self.dataArrayM.count < self.tablePage*CountPerPage) {
                    [self.yueBanTableView.mj_footer endRefreshingWithNoMoreData];
                }else{
                    [self.yueBanTableView.mj_footer endRefreshing];
                }
                [self.yueBanTableView reloadData];
            } else {
                [self.yueBanTableView.mj_footer endRefreshingWithNoMoreData];
                [MBProgressHUD showTipMessageInWindow:responseObject[@"message"]];
            }
        } else {
            if (self.tablePage == 1) {
                [self.yueBanTableView.mj_header endRefreshing];
            }else{
                [self.yueBanTableView.mj_footer endRefreshingWithNoMoreData];
            }
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
}


- (void)moreBarButtonItemClick {
    if (self.nwglXialaImageViewIsShowing) {
        [self.nwglXialaImageView removeFromSuperview];
        [self.backgroundAlphaView removeFromSuperview];
        self.nwglXialaImageViewIsShowing = false;
    } else {
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:self.backgroundAlphaView];
        [window addSubview:self.nwglXialaImageView];
        self.nwglXialaImageViewIsShowing = true;
    }
}

- (UIImageView *)nwglXialaImageView {
    if (!_nwglXialaImageView) {
        _nwglXialaImageView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth-1-SelectViewWidth, SafeAreaTopHeight-15, SelectViewWidth, SelectViewHeight)];
        _nwglXialaImageView.image = [UIImage imageNamed:@"nwgl_xiala"];
        _nwglXialaImageView.userInteractionEnabled = true;
        for (int i = 0; i < self.selectButtonsArray.count; i++) {
            UIButton *button  = [[UIButton alloc] initWithFrame:CGRectMake(0, 5+(SelectViewHeight-10)/self.selectButtonsArray.count*i, SelectViewWidth, (SelectViewHeight-10)/self.selectButtonsArray.count)];
            [button setImage:[UIImage imageNamed:self.selectButtonsArray[i][@"image"]] forState:UIControlStateNormal];
            [button setTitle:self.selectButtonsArray[i][@"title"] forState:UIControlStateNormal];
            button.tag = 1000+i;
            [button setTitleColor:hexColor(333333) forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:14];
            [_nwglXialaImageView addSubview:button];
            [button addTarget:self action:@selector(nwglXiaLaBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    return _nwglXialaImageView;
}
#pragma mark 新增 编辑 催办 督办 归档 流程图 按钮点击
- (void)nwglXiaLaBtnClicked:(UIButton*)button{
    [self.nwglXialaImageView removeFromSuperview];
    [self.backgroundAlphaView removeFromSuperview];
    self.nwglXialaImageViewIsShowing = false;
    switch (button.tag) {
        case 1000:
        {
            //新增
            LSYueBanInfoVC *lvc = [[LSYueBanInfoVC alloc]init];
            lvc.type = 2;
            WS
            lvc.HavedAddNewData = ^{
                [weakSelf.yueBanTableView.mj_header beginRefreshing];
            };
            [self.navigationController pushViewController:lvc animated:YES];
        }
            break;
        case 1001:
        {
            //办理
            if ([self.selectDict allKeys].count == 0) {
                [MBProgressHUD showWarnMessage:@"请选择编辑项目！"];
                return;
            }else{
                if (![self.selectDict[@"bpmStatus"] isEqualToString:@"1"]) {
                    [MBProgressHUD showWarnMessage:@"数据已上报，不可编辑！"];
                    return;
                }else{
                    LSYueBanInfoVC *lvc = [[LSYueBanInfoVC alloc]init];
                    lvc.type = 3;
                    lvc.dict = self.selectDict;
                    WS
                   lvc.HavedAddNewData = ^{
                       [weakSelf.yueBanTableView.mj_header beginRefreshing];
                   };
                    [self.navigationController pushViewController:lvc animated:YES];
                }
                
            }
            
        }
            break;
       
            
        default:
            break;
    }
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
//    [self.yueBanTableView.mj_header beginRefreshing];
}

- (UIView *)backgroundAlphaView {
    if (!_backgroundAlphaView) {
        _backgroundAlphaView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _backgroundAlphaView.backgroundColor = UIColor.clearColor;
        _backgroundAlphaView.userInteractionEnabled = true;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundAlphaViewTapped)];
        [_backgroundAlphaView addGestureRecognizer:tap];
    }
    return _backgroundAlphaView;
}

- (void)backgroundAlphaViewTapped {
    [self.nwglXialaImageView removeFromSuperview];
    [self.backgroundAlphaView removeFromSuperview];
    self.nwglXialaImageViewIsShowing = false;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArrayM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NiWenListCell *cell = [tableView dequeueReusableCellWithIdentifier:yueBanTableViewCellID];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"NiWenListCell" owner:nil options:nil]lastObject];
    }
    [cell configYueBanDict:self.dataArrayM[indexPath.row]];
    
    
    cell.xuanzhongbtnclicked = ^(BOOL selected) {
        for (NSInteger i = 0;  i < self.dataArrayM.count; i++) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:self.dataArrayM[i]];
            dict[@"isSelect"] = @"0";
            [self.dataArrayM replaceObjectAtIndex:i withObject:dict];
        }
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:self.dataArrayM[indexPath.row]];
        dict[@"isSelect"] = @"1";
        [self.dataArrayM replaceObjectAtIndex:indexPath.row withObject:dict];
        self.selectDict = self.dataArrayM[indexPath.row];
        [self.yueBanTableView reloadData];
    };
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    LSYueBanInfoVC *lvc = [[LSYueBanInfoVC alloc]init];
    lvc.type = 1;
    lvc.dict = self.dataArrayM[indexPath.row];
    [self .navigationController pushViewController:lvc animated:YES];
}
- (UITableView *)yueBanTableView {
    if (!_yueBanTableView) {
        _yueBanTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, headerSearchViewHeight, ScreenWidth, ScreenHeight-SafeAreaTopHeight-headerSearchViewHeight)];
        _yueBanTableView.delegate = self;
        _yueBanTableView.dataSource = self;
        _yueBanTableView.backgroundColor = hexColor(F0F0F0);
        _yueBanTableView.tableFooterView = [UIView new];
        _yueBanTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _yueBanTableView;
}

- (NSArray<NSDictionary *> *)selectButtonsArray {
    if (!_selectButtonsArray) {
        _selectButtonsArray = @[@{@"title":@"  新 增",@"image":@"xinzen"},
                                @{@"title":@"  编 辑",@"image":@"bianji"}];
    }
    return _selectButtonsArray;
}

- (NSMutableArray *)dataArrayM {
    if (!_dataArrayM) {
        _dataArrayM = [[NSMutableArray alloc] init];
    }
    return _dataArrayM;
}


@end
